<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<title>文件上传</title>
		<script src="https://unpkg.com/vue@next"></script>
		<!-- import CSS -->
		<link rel="stylesheet" href="https://unpkg.com/element-plus/lib/theme-chalk/index.css">
		<!-- import JavaScript -->
		<script src="https://unpkg.com/element-plus/lib/index.full.js"></script>
		<link href="https://releases.transloadit.com/uppy/v1.29.1/uppy.min.css" rel="stylesheet">
		<link href="css/index.css" rel="stylesheet">
	</head>
	<body>
		<div id="app">
			<el-card class="box-card">
				<template #header>
					<div class="card-header">
						<span>上传说明(选填)</span>
					</div>
				</template>
				<el-input id="fileDescription" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model = "message"
					placeholder="详细的文件说明可以更好的找到文件哦(͏ ˉ ꈊ ˉ)✧˖°">
				</el-input>
			</el-card>

			<el-card class="box-card">
				<template #header>
					<div class="card-header">
						<span>文件上传</span>
					</div>
				</template>
				<div class="card-body">
					<div id="drag-drop-area"></div>
				</div>
			</el-card>

			<!-- {{fileInfo}} -->
		</div>
	</body>
	<script src="https://releases.transloadit.com/uppy/v1.29.1/uppy.min.js"></script>
	<!-- 引入axios -->
	<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
	<script>
		// Vue部分
		const App = {
			data() {
				return {
					message: "",
				};
			},
			created() {

			}
		};
		const app = Vue.createApp(App);
		app.use(ElementPlus);
		app.mount("#app");

		// Uppy初始化
		var uppy = Uppy.Core()
			.use(Uppy.Dashboard, {
				inline: true,
				target: '#drag-drop-area',
				note: '支持所有文件类型的断点上传',
				width: 900,
				height: 750,
				theme: 'bark',
				metaFields: [
				    { id: 'name', name: 'Name', placeholder: 'file name' },
				    { id: 'license', name: 'License', placeholder: 'specify license' },
				    { id: 'caption', name: 'Caption', placeholder: 'describe what the image is about' },
				    { id: 'public', name: 'Public', render: function({value, onChange}, h) {
				      return h('input', { type: 'checkbox', onChange: (ev) => onChange(ev.target.checked ? 'on' : 'off'), defaultChecked: value === 'on' })
				    } }
				  ],
				locale: {
					strings: {
						// When `inline: false`, used as the screen reader label for the button that closes the modal.
						  closeModal: '关闭面板',
						  // Used as the screen reader label for the plus (+) button that shows the “Add more files” screen
						  addMoreFiles: '添加更多文件',
						  // TODO
						  addingMoreFiles: '添加更多文件',
						  // Used as the header for import panels, e.g., “Import from Google Drive”.
						  importFrom: 'Import from %{name}',
						  // When `inline: false`, used as the screen reader label for the dashboard modal.
						  dashboardWindowTitle: 'Uppy Dashboard Window (Press escape to close)',
						  // When `inline: true`, used as the screen reader label for the dashboard area.
						  dashboardTitle: 'Uppy Dashboard',
						  // Shown in the Informer when a link to a file was copied to the clipboard.
						  copyLinkToClipboardSuccess: 'Link copied to clipboard.',
						  // Used when a link cannot be copied automatically — the user has to select the text from the
						  // input element below this string.
						  copyLinkToClipboardFallback: 'Copy the URL below',
						  // Used as the hover title and screen reader label for buttons that copy a file link.
						  copyLink: 'Copy link',
						  // Used as the hover title and screen reader label for file source icons, e.g., “File source: Dropbox”.
						  fileSource: '完成进度: %{name}',
						  // Used as the label for buttons that accept and close panels (remote providers or metadata editor)
						  done: '完成',
						  // TODO
						  back: '返回',
						  // Used as the screen reader label for buttons that remove a file.
						  removeFile: 'Remove file',
						  // Used as the screen reader label for buttons that open the metadata editor panel for a file.
						  editFile: 'Edit file',
						  // Shown in the panel header for the metadata editor. Rendered as “Editing image.png”.
						  editing: 'Editing %{file}',
						  // Text for a button shown on the file preview, used to edit file metadata
						  edit: '编辑',
						  // Used as the screen reader label for the button that saves metadata edits and returns to the
						  // file list view.
						  finishEditingFile: 'Finish editing file',
						  // TODO
						  saveChanges: 'Save changes',
						  // Used as the label for the tab button that opens the system file selection dialog.
						  myDevice: '本地文件',
						  // Shown in the main dashboard area when no files have been selected, and one or more
						  // remote provider plugins are in use. %{browse} is replaced with a link that opens the system
						  // file selection dialog.
						  dropPasteImport: '将文件复制粘贴到这,或者 %{browse} 又或者导入文件从',
						  // Shown in the main dashboard area when no files have been selected, and no provider
						  // plugins are in use. %{browse} is replaced with a link that opens the system
						  // file selection dialog.
						  dropPaste: '拖拽或复制你的文件到这，又或者浏览本地文件',
						  // TODO
						  dropHint: '将你的文件拖拽到这',
						  // This string is clickable and opens the system file selection dialog.
						  browse: '浏览本地文件',
						  // Used as the hover text and screen reader label for file progress indicators when
						  // they have been fully uploaded.
						  uploadComplete: '上传完成',
						  // TODO
						  uploadPaused: 'Upload paused',
						  // Used as the hover text and screen reader label for the buttons to resume paused uploads.
						  resumeUpload: 'Resume upload',
						  // Used as the hover text and screen reader label for the buttons to pause uploads.
						  pauseUpload: '暂停',
						  // Used as the hover text and screen reader label for the buttons to retry failed uploads.
						  retryUpload: '重试',
						  // Used as the hover text and screen reader label for the buttons to cancel uploads.
						  cancelUpload: '取消',
						
						  // Used in a title, how many files are currently selected
						  xFilesSelected: {
						    0: '%{smart_count} file selected',
						    1: '%{smart_count} files selected'
						  },
						  // TODO
						  uploadingXFiles: {
						    0: 'Uploading %{smart_count} file',
						    1: 'Uploading %{smart_count} files'
						  },
						  // TODO
						  processingXFiles: {
						    0: 'Processing %{smart_count} file',
						    1: 'Processing %{smart_count} files'
						  },
						
						  // The "powered by Uppy" link at the bottom of the Dashboard.
						  // **NOTE**: This string is called `poweredBy2` for backwards compatibility reasons.
						  // See https://github.com/transloadit/uppy/pull/2077
						  poweredBy2: '本服务由小鸿同学提供',
						
						  // @uppy/status-bar strings:
						  uploading: '上传中',
						  complete: '上传完成'
					}
				}
			})
			.use(Uppy.Webcam, {
				inline: true,
				target: Uppy.Dashboard
			})
			// .use(Uppy.ScreenCapture, {
			// 	target: Uppy.Dashboard
			// })
			.use(Uppy.ImageEditor, {
				target: Uppy.Dashboard
			})
			.use(Uppy.Tus, {
				endpoint: 'http://119.29.67.157:8080/xiaohong/big/upload/'
			})
			
			// uppy.setMeta({ callback_url:'https://gateway.xiaohong.work/api/file/callback'})//自定义参数与普通上传类似（虽然支持自定义，建议不要自定义，海量文件情况下，自定义很可能给自已给埋坑）


		var fileInfo = {
			fileName: '',
			fileSize: '',
			extension: '',
			fileGroup: 'xiaohong',
			fileDescription: '',
			domain: 'https://file.xiaohong.work',
			path: "",
			md5: ''
		}
		
		var exchangeUrl = ""
		
		
		var exchage = function() {
			axios.get(exchangeUrl)
			.then( function (res){
				console.log(res)
				fileInfo.path = res.data.path
				fileInfo.md5 = res.data.md5
				console.log("fileInfo",fileInfo)
			}).catch(function(error) {
				console.log(error)
			})
		} 
		
		
		uppy.on('complete', async result => {
			console.log('successful files:', result.successful)
			console.log('failed files:', result.failed)
			if (result.successful.length > 0) {
				// 代表上传成功 遍历保存数据
				for (var i = 0; i < result.successful.length; i++) {
					console.log(JSON.stringify(result.successful[i]))
					this.fileInfo.fileName = result.successful[i].name
					this.fileInfo.fileSize = result.successful[i].size
					this.fileInfo.extension = result.successful[i].name.split('.').pop()
					this.fileInfo.fileDescription = document.getElementById("fileDescription").value
					console.log("value:" + document.getElementById("fileDescription").value)
					this.fileInfo.path = "/xiaohong"+result.successful[i].uploadURL.split('/xiaohong').pop()
					this.fileInfo.md5 = result.successful[i].uploadURL.split('/').pop()
					// axios.defaults.baseURL = ''
					axios.defaults.baseURL = 'https://gateway.xiaohong.work/api'
					// axios.defaults.baseURL = 'http://119.29.67.157:9004'
					// 换取文件信息
					exchangeUrl = result.successful[i].uploadURL.split('/big')[0]+"/upload?md5="+result.successful[i].uploadURL.split('/').pop()+"&output=json"
					// console.log(getInfoUrl)
					// axios.get("http://119.29.67.157:8080/xiaohong/upload?md5=d3dc22a87093ed479a3c255419565db6&output=json")
					// new Promise(exchange(getInfoUrl)).then(upload)
					// axios.get(exchangeUrl)
					// .then(async (res) => {
					// 	await console.log(res)
					// 	fileInfo.path = res.data.path
					// 	fileInfo.md5 = res.data.md5
					// 	await console.log("fileInfo")
					// 	console.log(fileInfo)
					// 	console.log("添加的信息")
					// 	console.log(JSON.stringify(fileInfo))
					// 	axios.post("https://gateway.xiaohong.work/api/file/add",{
					// 		...fileInfo,
					// 	}).then(function(res) {
					// 		console.log(JSON.stringify(res))
					// 		alert(res.data.message);
					// 	}).catch(function(error) {
					// 		console.log(error)
					// 	})
					// }).catch(function(error) {
					// 	console.log(error)
					// })
					axios.post("/file/add",{
						...this.fileInfo,
					}).then(function(res) {
						console.log(JSON.stringify(res))
						console.log(res.data.message);
					}).catch(function(error) {
						console.log(error)
					})
				}
				
			}
		})
	</script>
</html>
